package pl;

import gui.LogFrame;
import gui.SimplexTable;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.JFrame;

public class CC {
	private double[] targetFunction;
	private ArrayList<double[]> conditions;
	private boolean minimum;
	public static final int HIGHER_THAN = 9999;
	public static final int LOWER_THAN = -9999;
	public static final int EQUAL = 10000;
	private double[][] results;
	private double endValue;
	private LogFrame logArea;
	private JFrame frame;
	private boolean step;

	// Postać ograniczenia [1,1,1, HIGHER_THAN, 500]
	public CC(ArrayList<double[]> conds, double[] numerator,
			double[] denomitator, boolean min, JFrame frame, LogFrame f, boolean s) {
		this.conditions = conds;
		this.minimum = min;
		this.frame = frame;
		this.step = s;
		this.logArea = f;
		convertToCC(numerator, denomitator);
		findResult();
	}

	private void convertToCC(double[] numerator, double[] denomitator) {
		this.targetFunction = numerator;
		ArrayList<double[]> conds = new ArrayList<double[]>();
		for (double[] e : conditions) {
			double[] tmp = Arrays.copyOf(e, e.length + 1);
			tmp[tmp.length - 1] = 0;
			tmp[tmp.length - 2] = e[e.length - 2];
			tmp[tmp.length - 3] = -1 * e[e.length - 1];
			conds.add(tmp);
		}
		this.conditions = conds;
		double[] tmp = Arrays.copyOf(denomitator, denomitator.length + 2);
		tmp[tmp.length - 1] = 1;
		tmp[tmp.length - 2] = EQUAL;
		this.conditions.add(tmp);
	}

	public boolean findResult() {
		final Simplex simplex = new Simplex(conditions, targetFunction, minimum,
				logArea.getArea(), step);
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				SimplexTable st = new SimplexTable(simplex,
						true, logArea, CC.this);
				st.setVisible(true);
				frame.dispose();
			}
		});
		return true;
	}
	
	public boolean setResults(Simplex simplex){
		double[][] resultS = simplex.getOgrValues();
		double[][] baseNumbers = simplex.getBaseValues();
		endValue = simplex.getEndValue();
		results = new double[2][targetFunction.length];
		for (int i = 0; i < targetFunction.length; i++) {
			results[0][i] = i;
			for (int j = 0; j < baseNumbers.length; j++) {
				if (baseNumbers[j][0] == i) {
					results[1][i] = resultS[0][j];
					break;
				}
			}
		}
		if (results[1][targetFunction.length-1]<=0){
			return false;
		}
		return true;
	}
	
	public double[] showResults(){
		double[] res = new double[targetFunction.length];
		for (int i=0;i<targetFunction.length-1;i++){
			res[i] = results[1][i]/results[1][targetFunction.length-1];
		}
		res[res.length-1] = endValue;
		return res;
	}
	
}
